package com.rzico.sbl.ui.manual

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityManualBinding
import com.rzico.sbl.model.AddressData
import com.rzico.sbl.other.LinearNormalDecoration
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.viewmodel.ManualViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getColorEx
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.ifNotEmpty
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.textTrim
import com.xinnuo.common.extend.visibleValue
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.helper.sp2px
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ManualActivity : BaseActivity(R.layout.activity_manual) {

    private val mBinding by lazy { ActivityManualBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private var mScopeJob: Job? = null

    override fun getViewModel() = get<ManualViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关会员信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    view.addItemDecoration(
                        object : LinearNormalDecoration() {
                            override fun getHeaderName(index: Int): String {
                                val item = mList[index] as AddressData
                                return "${item.memberName}${item.memberMobile.ifNotEmpty { "-$it" }}"
                            }

                        }.apply {
                            setHeaderContentColor(getColorEx(R.color.background))
                            setTextColor(getColorEx(R.color.gray))

                            setHeaderHeight(dp2px(40f))
                            setFooterHeight(dp2px(13f))
                            setTextSize(sp2px(15f))

                            setOnHeaderClickListener {
                                val item = mList[it] as AddressData

                                (userRole in "1,2")
                                    .condition {
                                        startActivityEx<MemberDetailActivity>(
                                            "cardId" to item.cardId,
                                            "memberId" to item.memberId
                                        )
                                    }
                            }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<AddressData>(R.layout.item_manual_list) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_manual_card, "NO.${bean.cardNo}")
                                text(R.id.item_manual_name, bean.consignee)
                                text(R.id.item_manual_phone, bean.phone)
                                text(R.id.item_manual_adress, bean.address)
                                text(R.id.item_manual_owe, "会员：${bean.memberName}")

                                visibility(
                                    R.id.item_manual_def,
                                    visibleValue { bean.default }
                                )

                                with<ImageView>(R.id.item_manual_logo) {
                                    it.loadCircleImage(bean.logo, R.mipmap.default_user)
                                }

                                clicked {
                                    startActivityEx<ManualEditActivity>(
                                        "receiverId" to bean.id,
                                        "cardId" to bean.cardId,
                                        "memberId" to bean.memberId,
                                        "consignee" to bean.consignee,
                                        "phone" to bean.phone,
                                        "address" to bean.address
                                    )
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .manualSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"

                searchEdit.addTextChangedListener(
                    onTextChanged = { text, _, _, _ ->
                        text?.let {
                            searchClose.isGone = it.isEmpty()
                        }
                    },
                    afterTextChanged = {
                        mScopeJob?.let {
                            it.isActive
                                .condition {
                                    it.cancel()
                                }
                        }

                        mScopeJob = searchResult()
                    }
                )

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        searchEdit.text.isBlank()
                            .conditionElse(
                                actionTrue = { showToast("请输入姓名、手机号") },
                                actionFalse = {
                                    mKeyWord = searchEdit.textTrim
                                    updateList()
                                }
                            )
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text.isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入姓名、手机号") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    /**
     * 协程判断输入框停留时间
     */
    private fun searchResult() =
        lifecycleScope.launch {
            mKeyWord =
                mBinding
                    .manualSearch
                    .searchEdit
                    .textTrim

            mKeyWord.notEmpty {
                delay(1000)
            }

            updateList()
        }

    /**
     * 会员收货地址列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .memberList(
                page = index,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}